<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用，提供了一种有效的 MatLab 开源替代方案。使用它可以很方便的绘制出版质量级别的图形。">
<meta name="keywords" content="Python,数据分析,AI进阶">
<meta property="og:type" content="article">
<meta property="og:title" content="Matplotlib">
<meta property="og:url" content="https://rencheng.cc/2018/12/03/datascience/Matplotlib/index.html">
<meta property="og:site_name" content="PHOENIX&#39;s Blog">
<meta property="og:description" content="Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用，提供了一种有效的 MatLab 开源替代方案。使用它可以很方便的绘制出版质量级别的图形。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://object.renchengqi.com/blog/h0wl9.png">
<meta property="og:image" content="https://object.renchengqi.com/blog/ku31o.png">
<meta property="og:image" content="https://object.renchengqi.com/blog/x8an5.gif">
<meta property="og:image" content="https://object.renchengqi.com/blog/whkot.png">
<meta property="og:image" content="https://object.renchengqi.com/blog/omq6w.png">
<meta property="og:updated_time" content="2018-12-03T13:58:11.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Matplotlib">
<meta name="twitter:description" content="Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用，提供了一种有效的 MatLab 开源替代方案。使用它可以很方便的绘制出版质量级别的图形。">
<meta name="twitter:image" content="https://object.renchengqi.com/blog/h0wl9.png">



  <link rel="alternate" href="/atom.xml" title="PHOENIX's Blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://rencheng.cc/2018/12/03/datascience/Matplotlib/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Matplotlib | PHOENIX's Blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">PHOENIX's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Enjoy the journey of life</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://rencheng.cc/2018/12/03/datascience/Matplotlib/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="任成">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PHOENIX's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Matplotlib

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-12-03 21:58:11" itemprop="dateCreated datePublished" datetime="2018-12-03T21:58:11+08:00">2018-12-03</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/教程/" itemprop="url" rel="index"><span itemprop="name">教程</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                <span title="本文字数">19k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用，提供了一种有效的 MatLab 开源替代方案。使用它可以很方便的绘制出版质量级别的图形。<br><a id="more"></a></p>
<h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p><span class="exturl" data-url="aHR0cHM6Ly9tYXRwbG90bGliLm9yZy8=" title="https://matplotlib.org/">官网<i class="fa fa-external-link"></i></span></p>
<p><span class="exturl" data-url="aHR0cHM6Ly9tYXRwbG90bGliLm9yZy9nYWxsZXJ5L2luZGV4Lmh0bWw=" title="https://matplotlib.org/gallery/index.html">效果展示<i class="fa fa-external-link"></i></span></p>
<h3 id="matplotlib基本功能"><a href="#matplotlib基本功能" class="headerlink" title="matplotlib基本功能"></a>matplotlib基本功能</h3><ol>
<li>基本绘图 （在二维平面坐标系中绘制连续的线）<ol>
<li>设置线型、线宽和颜色  </li>
<li>设置坐标轴范围</li>
<li>设置坐标刻度</li>
<li>设置坐标轴</li>
<li>图例</li>
<li>特殊点</li>
<li>备注</li>
</ol>
</li>
<li>图形对象(图形窗口)<ol>
<li>子图</li>
<li>刻度定位器</li>
<li>刻度网格线</li>
<li>半对数坐标</li>
<li>散点图</li>
<li>填充</li>
<li>条形图（柱状图）</li>
<li>饼图</li>
<li>等高线图</li>
<li>热成像图</li>
<li>极坐标系</li>
<li>三维曲面</li>
<li>简单动画</li>
</ol>
</li>
</ol>
<h2 id="基本绘图"><a href="#基本绘图" class="headerlink" title="基本绘图"></a>基本绘图</h2><p>案例：绘制一条正弦曲线</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line"></span><br><span class="line"><span class="comment"># xarray: &lt;序列&gt; 水平坐标序列</span></span><br><span class="line"><span class="comment"># yarray: &lt;序列&gt; 垂直坐标序列</span></span><br><span class="line">mp.plot(xarray, yarray)</span><br><span class="line"><span class="comment">#显示图表</span></span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h3 id="绘制水平线与垂直线："><a href="#绘制水平线与垂直线：" class="headerlink" title="绘制水平线与垂直线："></a>绘制水平线与垂直线：</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line"></span><br><span class="line"><span class="comment"># vertical 绘制垂直线</span></span><br><span class="line">mp.vlines(vval, ymin, ymax, ...)</span><br><span class="line"><span class="comment"># horizotal 绘制水平线</span></span><br><span class="line">mp.hlines(xval, xmin, xmax, ...)</span><br><span class="line"><span class="comment">#显示图表</span></span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h3 id="线型、线宽和颜色"><a href="#线型、线宽和颜色" class="headerlink" title="线型、线宽和颜色"></a>线型、线宽和颜色</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#linestyle: '-' 实线  '--' 虚线  ':' 点线</span></span><br><span class="line"><span class="comment">#linewidth: 线宽</span></span><br><span class="line">	<span class="comment">#	数字</span></span><br><span class="line"><span class="comment">#color: &lt;关键字参数&gt; 颜色</span></span><br><span class="line">	<span class="comment">#	英文颜色单词 或 常见颜色英文单词首字母 或 #495434 或 (1,1,1) 或 (1,1,1,1)</span></span><br><span class="line"><span class="comment">#alpha: &lt;关键字参数&gt; 透明度</span></span><br><span class="line">	<span class="comment">#	浮点数值</span></span><br><span class="line">mp.plot(xarray, yarray, linestyle=<span class="string">''</span>, linewidth=<span class="number">1</span>, color=<span class="string">''</span>, alpha=<span class="number">0.5</span>)</span><br></pre></td></tr></table></figure>
<p>linestyle 见附录<br>linecolor 见附录</p>
<h3 id="设置坐标轴范围"><a href="#设置坐标轴范围" class="headerlink" title="设置坐标轴范围"></a>设置坐标轴范围</h3><p>案例：把坐标轴范围设置为 -π ~ π</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#x_limt_min:	&lt;float&gt; x轴范围最小值</span></span><br><span class="line"><span class="comment">#x_limit_max:	&lt;float&gt; x轴范围最大值</span></span><br><span class="line">mp.xlim(x_limt_min, x_limit_max)</span><br><span class="line"><span class="comment">#y_limt_min:	&lt;float&gt; y轴范围最小值</span></span><br><span class="line"><span class="comment">#y_limit_max:	&lt;float&gt; y轴范围最大值</span></span><br><span class="line">mp.ylim(y_limt_min, y_limit_max)</span><br></pre></td></tr></table></figure>
<p><strong>应用场景</strong><br>查看可视范围，例如只看第一象限；</p>
<h3 id="设置坐标刻度"><a href="#设置坐标刻度" class="headerlink" title="设置坐标刻度"></a>设置坐标刻度</h3><p>案例：把横坐标的刻度显示为：0, π/2, π, 3π/2, 2π</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#x_val_list: 	x轴刻度值序列</span></span><br><span class="line"><span class="comment">#x_text_list:	x轴刻度标签文本序列 [可选]</span></span><br><span class="line">mp.xticks(x_val_list , x_text_list )</span><br><span class="line"><span class="comment">#y_val_list: 	y轴刻度值序列</span></span><br><span class="line"><span class="comment">#y_text_list:	y轴刻度标签文本序列 [可选]</span></span><br><span class="line">mp.yticks(y_val_list , y_text_list )</span><br></pre></td></tr></table></figure>
<p><strong><em>刻度文本的特殊语法</em></strong> — <em>LaTex排版语法字符串</em></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">r'$x^n+y^n=z^n$'</span>,   <span class="string">r'$\int\frac&#123;1&#125;&#123;x&#125; dx = \ln |x| + C$'</span>,     <span class="string">r'$-\frac&#123;\pi&#125;&#123;2&#125;$'</span></span><br></pre></td></tr></table></figure>
<script type="math/tex; mode=display">
x^n+y^n=z^n,  \int\frac{1}{x} dx = \ln |x| + C,     -\frac{\pi}{2}</script><p>具体见附录</p>
<h3 id="设置坐标轴"><a href="#设置坐标轴" class="headerlink" title="设置坐标轴"></a>设置坐标轴</h3><p>坐标轴名：left / right / bottom / top</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 获取当前坐标轴对象，&#123;'left':左轴,'right':右轴,'bottom':下轴,'top':上轴 &#125;</span></span><br><span class="line">ax = mp.gca()</span><br><span class="line"><span class="comment"># 获取其中某个坐标轴</span></span><br><span class="line">axis = ax.spines[<span class="string">'坐标轴名'</span>]</span><br><span class="line"><span class="comment"># 设置坐标轴的位置。 该方法需要传入2个元素的元组作为参数</span></span><br><span class="line"><span class="comment"># type: &lt;str&gt; 移动坐标轴的参照类型  一般为'data' (以数据的值作为移动参照值)</span></span><br><span class="line"><span class="comment"># val:  参照值</span></span><br><span class="line">axis.set_position((type, val))</span><br><span class="line"><span class="comment"># 设置坐标轴的颜色</span></span><br><span class="line"><span class="comment"># color: &lt;str&gt; 颜色值字符串</span></span><br><span class="line">axis.set_color(color)</span><br></pre></td></tr></table></figure>
<p>案例：设置坐标轴至中心。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 设置坐标轴</span></span><br><span class="line">ax = mp.gca()</span><br><span class="line">ax.spines[<span class="string">'top'</span>].set_color(<span class="string">'none'</span>)</span><br><span class="line">ax.spines[<span class="string">'right'</span>].set_color(<span class="string">'none'</span>)</span><br><span class="line">ax.spines[<span class="string">'left'</span>].set_position((<span class="string">'data'</span>, <span class="number">0</span>))</span><br><span class="line">ax.spines[<span class="string">'bottom'</span>].set_position((<span class="string">'data'</span>, <span class="number">0</span>))</span><br><span class="line">mp.yticks([<span class="number">-1</span>, <span class="number">-0.5</span>, <span class="number">0.5</span>, <span class="number">1</span>])</span><br></pre></td></tr></table></figure>
<h3 id="图例"><a href="#图例" class="headerlink" title="图例"></a>图例</h3><blockquote>
<p>图例就是标注哪条线是什么意思</p>
</blockquote>
<p>显示两条曲线的图例，并测试loc属性。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 再绘制曲线时定义曲线的label</span></span><br><span class="line"><span class="comment"># label: &lt;关键字参数 str&gt; 支持LaTex排版语法字符串</span></span><br><span class="line">mp.plot(xarray, yarray ... label=<span class="string">''</span>, ...)</span><br><span class="line"><span class="comment"># 设置图例的位置</span></span><br><span class="line"><span class="comment"># loc: &lt;关键字参数&gt; 制定图例的显示位置 (若不设置loc，则显示默认位置)</span></span><br><span class="line"><span class="comment">#	 ===============   =============</span></span><br><span class="line"><span class="comment">#    Location String   Location Code</span></span><br><span class="line"><span class="comment">#    ===============   =============</span></span><br><span class="line"><span class="comment">#    'best'            0</span></span><br><span class="line"><span class="comment">#    'upper right'     1</span></span><br><span class="line"><span class="comment">#    'upper left'      2</span></span><br><span class="line"><span class="comment">#    'lower left'      3</span></span><br><span class="line"><span class="comment">#    'lower right'     4</span></span><br><span class="line"><span class="comment">#    'right'           5</span></span><br><span class="line"><span class="comment">#    'center left'     6</span></span><br><span class="line"><span class="comment">#    'center right'    7</span></span><br><span class="line"><span class="comment">#    'lower center'    8</span></span><br><span class="line"><span class="comment">#    'upper center'    9</span></span><br><span class="line"><span class="comment">#    'center'          10</span></span><br><span class="line"><span class="comment">#    ===============   =============</span></span><br><span class="line">mp.legend(loc=<span class="string">''</span>)</span><br></pre></td></tr></table></figure>
<h3 id="特殊点"><a href="#特殊点" class="headerlink" title="特殊点"></a>特殊点</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># xarray: &lt;序列&gt; 所有需要标注点的水平坐标组成的序列</span></span><br><span class="line"><span class="comment"># yarray: &lt;序列&gt; 所有需要标注点的垂直坐标组成的序列</span></span><br><span class="line">mp.scatter(xarray, yarray, </span><br><span class="line">           marker=<span class="string">''</span>, 		<span class="comment">#点型 ~ matplotlib.markers</span></span><br><span class="line">           s=<span class="number">60</span>, 			<span class="comment">#大小</span></span><br><span class="line">           edgecolor=<span class="string">''</span>, 	<span class="comment">#边缘色</span></span><br><span class="line">           facecolor=<span class="string">''</span>,	<span class="comment">#填充色</span></span><br><span class="line">           zorder=<span class="number">3</span>			<span class="comment">#绘制图层编号 （编号越大，图层越靠上）</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p><em>marker点型可参照：help(matplotlib.markers)</em></p>
<p>也可参照附录：point样式</p>
<h3 id="备注"><a href="#备注" class="headerlink" title="备注"></a>备注</h3><p>为在某条曲线上的点添加备注，指明函数方程与值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 在图表中为某个点添加备注。包含备注文本，备注箭头等图像的设置。</span></span><br><span class="line">mp.annotate(</span><br><span class="line">    <span class="string">r'$\frac&#123;\pi&#125;&#123;2&#125;$'</span>, <span class="comment">#备注中显示的文本内容</span></span><br><span class="line">    xycoords=<span class="string">'data'</span>,    <span class="comment">#备注目标点所使用的坐标系（data表示数据坐标系）</span></span><br><span class="line">    xy=(x, y),          <span class="comment">#备注目标点的坐标</span></span><br><span class="line">    textcoords=<span class="string">'offset points'</span>, <span class="comment">#备注文本所使用的坐标系（offset points表示参照点的偏移坐标系）</span></span><br><span class="line">    xytext=(x, y),      <span class="comment">#备注文本的坐标</span></span><br><span class="line">    fontsize=<span class="number">14</span>,        <span class="comment">#备注文本的字体大小</span></span><br><span class="line">    arrowprops=dict()   <span class="comment">#使用字典定义文本指向目标点的箭头样式</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p><strong>arrowprops参数使用字典定义指向目标点的箭头样式</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#arrowprops字典参数的常用key</span></span><br><span class="line">arrowprops=dict(</span><br><span class="line">    arrowstyle=<span class="string">''</span>,		<span class="comment">#定义箭头样式</span></span><br><span class="line">    connectionstyle=<span class="string">''</span>	<span class="comment">#定义连接线的样式</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p><strong>箭头样式（arrowstyle）字符串如下</strong></p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">============   =============================================</span><br><span class="line">Name           Attrs</span><br><span class="line">============   =============================================</span><br><span class="line">  '-'          None</span><br><span class="line">  '-&gt;'         head_length=<span class="number">0.4</span>,head_width=<span class="number">0.2</span></span><br><span class="line">  '-['         widthB=<span class="number">1.0</span>,lengthB=<span class="number">0.2</span>,angleB=None</span><br><span class="line">  '|-|'        widthA=<span class="number">1.0</span>,widthB=<span class="number">1.0</span></span><br><span class="line">  '-|&gt;'        head_length=<span class="number">0.4</span>,head_width=<span class="number">0.2</span></span><br><span class="line">  '&lt;-'         head_length=<span class="number">0.4</span>,head_width=<span class="number">0.2</span></span><br><span class="line">  '&lt;-&gt;'        head_length=<span class="number">0.4</span>,head_width=<span class="number">0.2</span></span><br><span class="line">  '&lt;|-'        head_length=<span class="number">0.4</span>,head_width=<span class="number">0.2</span></span><br><span class="line">  '&lt;|-|&gt;'      head_length=<span class="number">0.4</span>,head_width=<span class="number">0.2</span></span><br><span class="line">  'fancy'      head_length=<span class="number">0.4</span>,head_width=<span class="number">0.4</span>,tail_width=<span class="number">0.4</span></span><br><span class="line">  'simple'     head_length=<span class="number">0.5</span>,head_width=<span class="number">0.5</span>,tail_width=<span class="number">0.2</span></span><br><span class="line">  'wedge'      tail_width=<span class="number">0.3</span>,shrink_factor=<span class="number">0.5</span></span><br><span class="line">============   =============================================</span><br></pre></td></tr></table></figure>
<p><strong>连接线样式（connectionstyle）字符串如下</strong></p>
<div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:left">Name</th>
<th style="text-align:left">Attrs</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">‘angle’</td>
<td style="text-align:left">angleA=90,angleB=0,rad=0.0</td>
</tr>
<tr>
<td style="text-align:left">‘angle3’</td>
<td style="text-align:left">angleA=90,angleB=0`</td>
</tr>
<tr>
<td style="text-align:left">‘arc’</td>
<td style="text-align:left">angleA=0,angleB=0,armA=None,armB=None,rad=0.0</td>
</tr>
<tr>
<td style="text-align:left">‘arc3’</td>
<td style="text-align:left">rad=0.0</td>
</tr>
<tr>
<td style="text-align:left">‘bar’</td>
<td style="text-align:left">armA=0.0,armB=0.0,fraction=0.3,angle=None</td>
</tr>
</tbody>
</table>
</div>
<h2 id="图形对象（图形窗口）"><a href="#图形对象（图形窗口）" class="headerlink" title="图形对象（图形窗口）"></a>图形对象（图形窗口）</h2><p>绘制两个窗口，一起显示。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 手动构建 matplotlib 窗口</span></span><br><span class="line">mp.figure(</span><br><span class="line">    <span class="string">'A'</span>,            <span class="comment">#窗口标题栏文本 </span></span><br><span class="line">    facecolor=<span class="string">''</span>		<span class="comment">#图表背景色</span></span><br><span class="line">)</span><br><span class="line">mp.figure(<span class="string">'B'</span>)</span><br><span class="line">mp.figure(<span class="string">'A'</span>)  <span class="comment"># 把A创建置为当前窗口</span></span><br><span class="line">mp.plot(....) <span class="comment"># 将会作用在A窗口中</span></span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<p>mp.figure方法不仅可以构建一个新窗口，如果已经构建过title=’xxx’的窗口，又使用figure方法构建了title=’xxx’ 的窗口的话，mp将不会创建新的窗口，而是把title=’xxx’的窗口置为当前操作窗口。</p>
<p><strong>设置当前窗口的参数</strong></p>
<p>案例：测试窗口相关参数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 设置图表标题 显示在图表上方</span></span><br><span class="line">mp.title(title, fontsize=<span class="number">12</span>)</span><br><span class="line"><span class="comment"># 设置水平轴的文本</span></span><br><span class="line">mp.xlabel(x_label_str, fontsize=<span class="number">12</span>)</span><br><span class="line"><span class="comment"># 设置垂直轴的文本</span></span><br><span class="line">mp.ylabel(y_label_str, fontsize=<span class="number">12</span>)</span><br><span class="line"><span class="comment"># 设置刻度参数   labelsize设置刻度字体大小</span></span><br><span class="line">mp.tick_params(labelsize=<span class="number">8</span>)</span><br><span class="line"><span class="comment"># 设置图表网格线  linestyle设置网格线的样式</span></span><br><span class="line">	<span class="comment">#	-  or solid 粗线</span></span><br><span class="line">	<span class="comment">#   -- or dashed 虚线</span></span><br><span class="line">	<span class="comment">#   -. or dashdot 点虚线</span></span><br><span class="line">	<span class="comment">#   :  or dotted 点线</span></span><br><span class="line">mp.grid(linestyle=<span class="string">''</span>)</span><br><span class="line"><span class="comment"># 设置紧凑布局，把图表相关参数都显示在窗口中</span></span><br><span class="line">mp.tight_layout()</span><br></pre></td></tr></table></figure>
<h3 id="子图"><a href="#子图" class="headerlink" title="子图"></a>子图</h3><p><strong>矩阵式布局</strong></p>
<p>绘制矩阵式子图布局相关API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">mp.figure(<span class="string">'Subplot Layout'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line"><span class="comment"># 拆分矩阵</span></span><br><span class="line">	<span class="comment"># rows:	行数</span></span><br><span class="line">    <span class="comment"># cols:	列数</span></span><br><span class="line">    <span class="comment"># num:	编号</span></span><br><span class="line">mp.subplot(rows, cols, num)</span><br><span class="line">	<span class="comment">#	1 2 3</span></span><br><span class="line">	<span class="comment">#	4 5 6</span></span><br><span class="line">	<span class="comment">#	7 8 9 </span></span><br><span class="line">mp.subplot(<span class="number">3</span>, <span class="number">3</span>, <span class="number">5</span>)		<span class="comment">#操作3*3的矩阵中编号为5的子图</span></span><br><span class="line">mp.plot()</span><br><span class="line">mp.subplot(<span class="number">3</span>, <span class="number">3</span>, <span class="number">1</span>)		<span class="comment">#操作3*3的矩阵中编号为1的子图</span></span><br><span class="line">mp.plot()</span><br><span class="line">mp.subplot(<span class="number">335</span>)			<span class="comment">#简写</span></span><br></pre></td></tr></table></figure>
<p>案例：绘制9宫格矩阵式子图，每个子图中写一个数字。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">mp.figure(<span class="string">'Subplot Layout'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">9</span>):</span><br><span class="line">	mp.subplot(<span class="number">3</span>, <span class="number">3</span>, i+<span class="number">1</span>)</span><br><span class="line">	mp.text(</span><br><span class="line">		<span class="number">0.5</span>, <span class="number">0.5</span>, i+<span class="number">1</span>, </span><br><span class="line">		ha=<span class="string">'center'</span>,</span><br><span class="line">		va=<span class="string">'center'</span>,</span><br><span class="line">		size=<span class="number">36</span>,</span><br><span class="line">		alpha=<span class="number">0.5</span></span><br><span class="line">	)</span><br><span class="line">	mp.xticks([])</span><br><span class="line">	mp.yticks([])</span><br><span class="line"></span><br><span class="line">mp.tight_layout()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<p><strong>网格式布局</strong></p>
<p>网格式布局支持单元格的合并。</p>
<p>绘制网格式子图布局相关API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> matplotlib.gridspec <span class="keyword">as</span> mg</span><br><span class="line">mp.figure(<span class="string">'Grid Layout'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line"><span class="comment"># 调用GridSpec方法拆分网格式布局</span></span><br><span class="line"><span class="comment"># rows:	行数</span></span><br><span class="line"><span class="comment"># cols:	列数</span></span><br><span class="line"><span class="comment"># gs = mg.GridSpec(rows, cols)	拆分成3行3列</span></span><br><span class="line">gs = mg.GridSpec(<span class="number">3</span>, <span class="number">3</span>)	</span><br><span class="line"><span class="comment"># 合并0行与0、1列为一个子图表</span></span><br><span class="line">mp.subplot(gs[<span class="number">0</span>, :<span class="number">2</span>])</span><br><span class="line">mp.text(<span class="number">0.5</span>, <span class="number">0.5</span>, <span class="string">'1'</span>, ha=<span class="string">'center'</span>, va=<span class="string">'center'</span>, size=<span class="number">36</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<p>案例：绘制一个自定义网格布局。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> matplotlib.gridspec <span class="keyword">as</span> mg</span><br><span class="line">mp.figure(<span class="string">'GridLayout'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">gridsubs = mp.GridSpec(<span class="number">3</span>, <span class="number">3</span>)</span><br><span class="line"><span class="comment"># 合并0行、0/1列为一个子图</span></span><br><span class="line">mp.subplot(gridsubs[<span class="number">0</span>, :<span class="number">2</span>])</span><br><span class="line">mp.text(<span class="number">0.5</span>, <span class="number">0.5</span>, <span class="number">1</span>, ha=<span class="string">'center'</span>, va=<span class="string">'center'</span>, size=<span class="number">36</span>)</span><br><span class="line">mp.tight_layout()</span><br><span class="line">mp.xticks([])</span><br><span class="line">mp.yticks([])</span><br></pre></td></tr></table></figure>
<p><strong>自由式布局</strong></p>
<p>自由式布局相关API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mp.figure(<span class="string">'Flow Layout'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line"><span class="comment"># 设置图标的位置，给出左下角点坐标与宽高即可</span></span><br><span class="line"><span class="comment"># left_bottom_x: 坐下角点x坐标</span></span><br><span class="line"><span class="comment"># left_bottom_x: 坐下角点y坐标</span></span><br><span class="line"><span class="comment"># width:		 宽度</span></span><br><span class="line"><span class="comment"># height:		 高度</span></span><br><span class="line"><span class="comment"># mp.axes([left_bottom_x, left_bottom_y, width, height])</span></span><br><span class="line">mp.axes([<span class="number">0.03</span>, <span class="number">0.03</span>, <span class="number">0.94</span>, <span class="number">0.94</span>])</span><br><span class="line">mp.text(<span class="number">0.5</span>, <span class="number">0.5</span>, <span class="string">'1'</span>, ha=<span class="string">'center'</span>, va=<span class="string">'center'</span>, size=<span class="number">36</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<p>案例：测试自由式布局，定位子图。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">mp.figure(<span class="string">'FlowLayout'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line"></span><br><span class="line">mp.axes([<span class="number">0.1</span>, <span class="number">0.2</span>, <span class="number">0.5</span>, <span class="number">0.3</span>])</span><br><span class="line">mp.text(<span class="number">0.5</span>, <span class="number">0.5</span>, <span class="string">'1'</span>, ha=<span class="string">'center'</span>, va=<span class="string">'center'</span>, size=<span class="number">36</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h3 id="刻度定位器"><a href="#刻度定位器" class="headerlink" title="刻度定位器"></a>刻度定位器</h3><p>刻度定位器相关API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 获取当前坐标轴</span></span><br><span class="line">ax = mp.gca()</span><br><span class="line"><span class="comment"># 设置水平坐标轴的主刻度定位器</span></span><br><span class="line">ax.xaxis.set_major_locator(mp.NullLocator())</span><br><span class="line"><span class="comment"># 设置水平坐标轴的次刻度定位器为多点定位器，间隔0.1</span></span><br><span class="line">ax.xaxis.set_minor_locator(mp.MultipleLocator(<span class="number">0.1</span>))</span><br></pre></td></tr></table></figure>
<p>案例：绘制一个数轴。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">mp.figure(<span class="string">'Locators'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line"><span class="comment"># 获取当前坐标轴</span></span><br><span class="line">ax = mp.gca()</span><br><span class="line"><span class="comment"># 隐藏除底轴以外的所有坐标轴</span></span><br><span class="line">ax.spines[<span class="string">'left'</span>].set_color(<span class="string">'none'</span>)</span><br><span class="line">ax.spines[<span class="string">'top'</span>].set_color(<span class="string">'none'</span>)</span><br><span class="line">ax.spines[<span class="string">'right'</span>].set_color(<span class="string">'none'</span>)</span><br><span class="line"><span class="comment"># 将底坐标轴调整到子图中心位置</span></span><br><span class="line">ax.spines[<span class="string">'bottom'</span>].set_position((<span class="string">'data'</span>, <span class="number">0</span>))</span><br><span class="line"><span class="comment"># 设置水平坐标轴的主刻度定位器</span></span><br><span class="line">ax.xaxis.set_major_locator(mp.NullLocator())</span><br><span class="line"><span class="comment"># 设置水平坐标轴的次刻度定位器为多点定位器，间隔0.1</span></span><br><span class="line">ax.xaxis.set_minor_locator(mp.MultipleLocator(<span class="number">0.1</span>))</span><br><span class="line"><span class="comment"># 标记所用刻度定位器类名 </span></span><br><span class="line">mp.text(<span class="number">5</span>, <span class="number">0.3</span>, <span class="string">'NullLocator()'</span>, ha=<span class="string">'center'</span>, size=<span class="number">12</span>)</span><br></pre></td></tr></table></figure>
<p>案例：使用for循环测试刻度器样式：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">locators = [<span class="string">'mp.NullLocator()'</span>, <span class="string">'mp.MaxNLocator(nbins=4)'</span>]</span><br><span class="line">	</span><br><span class="line"><span class="keyword">for</span> i, locator <span class="keyword">in</span> enumerate(locators):</span><br><span class="line">    mp.subplot(len(locators), <span class="number">1</span>, i+<span class="number">1</span>)</span><br><span class="line">	mp.xlim(<span class="number">0</span>, <span class="number">10</span>)</span><br><span class="line">	mp.ylim(<span class="number">-1</span>, <span class="number">1</span>)</span><br><span class="line">	mp.yticks([])</span><br><span class="line">	<span class="comment"># 获取当前坐标轴</span></span><br><span class="line">	ax = mp.gca()</span><br><span class="line">	<span class="comment"># 隐藏除底轴以外的所有坐标轴</span></span><br><span class="line">	ax.spines[<span class="string">'left'</span>].set_color(<span class="string">'none'</span>)</span><br><span class="line">	ax.spines[<span class="string">'top'</span>].set_color(<span class="string">'none'</span>)</span><br><span class="line">	ax.spines[<span class="string">'right'</span>].set_color(<span class="string">'none'</span>)</span><br><span class="line">	<span class="comment"># 将底坐标轴调整到子图中心位置</span></span><br><span class="line">	ax.spines[<span class="string">'bottom'</span>].set_position((<span class="string">'data'</span>, <span class="number">0</span>))</span><br><span class="line">	<span class="comment"># 设置水平坐标轴的主刻度定位器</span></span><br><span class="line">	ax.xaxis.set_major_locator(eval( ))</span><br><span class="line">	<span class="comment"># 设置水平坐标轴的次刻度定位器为多点定位器，间隔0.1</span></span><br><span class="line">	ax.xaxis.set_minor_locator(mp.MultipleLocator(<span class="number">0.1</span>))</span><br><span class="line">	mp.plot(np.arange(<span class="number">11</span>), np.zeros(<span class="number">11</span>), c=<span class="string">'none'</span>)</span><br><span class="line">	<span class="comment"># 标记所用刻度定位器类名</span></span><br><span class="line">	mp.text(<span class="number">5</span>, <span class="number">0.3</span>, locator, ha=<span class="string">'center'</span>, size=<span class="number">12</span>)</span><br></pre></td></tr></table></figure>
<p>常用刻度器如下</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 空定位器：不绘制刻度</span></span><br><span class="line">mp.NullLocator()</span><br><span class="line"><span class="comment"># 最大值定位器：</span></span><br><span class="line"><span class="comment"># 最多绘制nbins+1个刻度</span></span><br><span class="line">mp.MaxNLocator(nbins=<span class="number">3</span>)</span><br><span class="line"><span class="comment"># 定点定位器：根据locs参数中的位置绘制刻度</span></span><br><span class="line">mp.FixedLocator(locs=[<span class="number">0</span>, <span class="number">2.5</span>, <span class="number">5</span>, <span class="number">7.5</span>, <span class="number">10</span>])</span><br><span class="line"><span class="comment"># 自动定位器：由系统自动选择刻度的绘制位置</span></span><br><span class="line">mp.AutoLocator()</span><br><span class="line"><span class="comment"># 索引定位器：由offset确定起始刻度，由base确定相邻刻度的间隔</span></span><br><span class="line">mp.IndexLocator(offset=<span class="number">0.5</span>, base=<span class="number">1.5</span>)</span><br><span class="line"><span class="comment"># 多点定位器：从0开始，按照参数指定的间隔(缺省1)绘制刻度</span></span><br><span class="line">mp.MultipleLocator()</span><br><span class="line"><span class="comment"># 线性定位器：等分numticks-1份，绘制numticks个刻度</span></span><br><span class="line">mp.LinearLocator(numticks=<span class="number">21</span>)</span><br><span class="line"><span class="comment"># 对数定位器：以base为底，绘制刻度</span></span><br><span class="line">mp.LogLocator(base=<span class="number">2</span>)</span><br></pre></td></tr></table></figure>
<h3 id="刻度网格线"><a href="#刻度网格线" class="headerlink" title="刻度网格线"></a>刻度网格线</h3><p>绘制刻度网格线的相关API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">ax = mp.gca()</span><br><span class="line"><span class="comment">#绘制刻度网格线</span></span><br><span class="line">ax.grid(</span><br><span class="line">    which=<span class="string">''</span>,		<span class="comment"># 'major'/'minor' &lt;-&gt; '主刻度'/'次刻度' </span></span><br><span class="line">    axis=<span class="string">''</span>,		<span class="comment"># 'x'/'y'/'both' &lt;-&gt; 绘制x或y轴</span></span><br><span class="line">    linewidth=<span class="number">1</span>, 	<span class="comment"># 线宽</span></span><br><span class="line">    linestyle=<span class="string">''</span>, 	<span class="comment"># 线型</span></span><br><span class="line">    color=<span class="string">''</span>,		<span class="comment"># 颜色</span></span><br><span class="line">    alpha=<span class="number">0.5</span>		<span class="comment"># 透明度</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>案例：绘制曲线 [1, 10, 100, 1000, 100, 10, 1]，然后设置刻度网格线，测试刻度网格线的参数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">y = np.array([<span class="number">1</span>, <span class="number">10</span>, <span class="number">100</span>, <span class="number">1000</span>, <span class="number">100</span>, <span class="number">10</span>, <span class="number">1</span>])</span><br><span class="line">mp.figure(<span class="string">'Normal &amp; Log'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.subplot(<span class="number">211</span>)</span><br><span class="line">mp.title(<span class="string">'Normal'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">ax = mp.gca()</span><br><span class="line">ax.xaxis.set_major_locator(mp.MultipleLocator(<span class="number">1.0</span>))</span><br><span class="line">ax.xaxis.set_minor_locator(mp.MultipleLocator(<span class="number">0.1</span>))</span><br><span class="line">ax.yaxis.set_major_locator(mp.MultipleLocator(<span class="number">250</span>))</span><br><span class="line">ax.yaxis.set_minor_locator(mp.MultipleLocator(<span class="number">50</span>))</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">ax.grid(which=<span class="string">'major'</span>, axis=<span class="string">'both'</span>, linewidth=<span class="number">0.75</span>,</span><br><span class="line">        linestyle=<span class="string">'-'</span>, color=<span class="string">'orange'</span>)</span><br><span class="line">ax.grid(which=<span class="string">'minor'</span>, axis=<span class="string">'both'</span>, linewidth=<span class="number">0.25</span>,</span><br><span class="line">        linestyle=<span class="string">'-'</span>, color=<span class="string">'orange'</span>)</span><br><span class="line">mp.plot(y, <span class="string">'o-'</span>, c=<span class="string">'dodgerblue'</span>, label=<span class="string">'plot'</span>)</span><br><span class="line">mp.legend()</span><br></pre></td></tr></table></figure>
<h3 id="半对数坐标"><a href="#半对数坐标" class="headerlink" title="半对数坐标"></a>半对数坐标</h3><p>y轴将以指数方式递增。 基于半对数坐标绘制第二个子图，表示曲线：[1, 10, 100, 1000, 100, 10, 1]。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mp.figure(<span class="string">'Grid'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">y = [<span class="number">1</span>, <span class="number">10</span>, <span class="number">100</span>, <span class="number">1000</span>, <span class="number">100</span>, <span class="number">10</span>, <span class="number">1</span>]</span><br><span class="line">mp.semilogy(y)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h3 id="散点图"><a href="#散点图" class="headerlink" title="散点图"></a>散点图</h3><p>可以通过每个点的坐标、颜色、大小和形状表示不同的特征值。</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>身高</th>
<th>体重</th>
<th>性别</th>
<th>年龄段</th>
<th>种族</th>
</tr>
</thead>
<tbody>
<tr>
<td>180</td>
<td>80</td>
<td>男</td>
<td>中年</td>
<td>亚洲</td>
</tr>
<tr>
<td>160</td>
<td>50</td>
<td>女</td>
<td>青少</td>
<td>美洲</td>
</tr>
</tbody>
</table>
</div>
<p>绘制散点图的相关API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mp.scatter(</span><br><span class="line">    x, 					<span class="comment"># x轴坐标数组</span></span><br><span class="line">    y,					<span class="comment"># y轴坐标数组</span></span><br><span class="line">    marker=<span class="string">''</span>, 			<span class="comment"># 点型</span></span><br><span class="line">    s=<span class="number">10</span>,				<span class="comment"># 大小</span></span><br><span class="line">    color=<span class="string">''</span>,			<span class="comment"># 颜色</span></span><br><span class="line">    edgecolor=<span class="string">''</span>, 		<span class="comment"># 边缘颜色</span></span><br><span class="line">    facecolor=<span class="string">''</span>,		<span class="comment"># 填充色</span></span><br><span class="line">    zorder=<span class="string">''</span>			<span class="comment"># 图层序号</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>numpy.random提供了normal函数用于产生符合 正态分布 的随机数 </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">n = <span class="number">100</span></span><br><span class="line"><span class="comment"># 172:	期望值</span></span><br><span class="line"><span class="comment"># 10:	标准差</span></span><br><span class="line"><span class="comment"># n:	数字生成数量</span></span><br><span class="line">x = np.random.normal(<span class="number">172</span>, <span class="number">20</span>, n)</span><br><span class="line">y = np.random.normal(<span class="number">60</span>, <span class="number">10</span>, n)</span><br></pre></td></tr></table></figure>
<p>案例：绘制平面散点图。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mp.figure(<span class="string">'scatter'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'scatter'</span>)</span><br><span class="line">mp.scatter(x, y)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<p>设置点的颜色</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">mp.scatter(x, y, c=<span class="string">'red'</span>)	</span><br><span class="line"><span class="comment">#直接设置颜色</span></span><br><span class="line">d = (x<span class="number">-172</span>)**<span class="number">2</span> + (y<span class="number">-60</span>)**<span class="number">2</span></span><br><span class="line">mp.scatter(x, y, c=d, cmap=<span class="string">'jet'</span>)	<span class="comment">#以c作为参数，取cmap颜色映射表中的颜色值</span></span><br></pre></td></tr></table></figure>
<p><em>cmap颜色映射表参附录cmap颜色映射表</em></p>
<h3 id="填充"><a href="#填充" class="headerlink" title="填充"></a>填充</h3><p>以某种颜色自动填充两条曲线的闭合区域。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mp.fill_between(</span><br><span class="line">	x,				<span class="comment"># x轴的水平坐标</span></span><br><span class="line">    sin_x,			<span class="comment"># 下边界曲线上点的垂直坐标</span></span><br><span class="line">    cos_x,			<span class="comment"># 上边界曲线上点的垂直坐标</span></span><br><span class="line">    sin_x&lt;cos_x, 	<span class="comment"># 填充条件，为True时填充</span></span><br><span class="line">    color=<span class="string">''</span>, 		<span class="comment"># 填充颜色</span></span><br><span class="line">    alpha=<span class="number">0.2</span>		<span class="comment"># 透明度</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>案例：绘制两条曲线： sin_x = sin(x)    cos_x = cos(x / 2) / 2    [0-8π]  </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">n = <span class="number">1000</span></span><br><span class="line">x = np.linspace(<span class="number">0</span>, <span class="number">8</span> * np.pi, n)</span><br><span class="line">sin_y = np.sin(x)</span><br><span class="line">cos_y = np.cos(x / <span class="number">2</span>) / <span class="number">2</span></span><br><span class="line">mp.figure(<span class="string">'Fill'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Fill'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.plot(x, sin_y, c=<span class="string">'dodgerblue'</span>,</span><br><span class="line">        label=<span class="string">r'$y=sin(x)$'</span>)</span><br><span class="line">mp.plot(x, cos_y, c=<span class="string">'orangered'</span>,</span><br><span class="line">        label=<span class="string">r'$y=\frac&#123;1&#125;&#123;2&#125;cos(\frac&#123;x&#125;&#123;2&#125;)$'</span>)</span><br><span class="line">mp.fill_between(x, cos_y, sin_y, cos_y &lt; sin_y,</span><br><span class="line">                color=<span class="string">'dodgerblue'</span>, alpha=<span class="number">0.5</span>)</span><br><span class="line">mp.fill_between(x, cos_y, sin_y, cos_y &gt; sin_y,</span><br><span class="line">                color=<span class="string">'orangered'</span>, alpha=<span class="number">0.5</span>)</span><br><span class="line">mp.legend()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h3 id="条形图（柱状图）"><a href="#条形图（柱状图）" class="headerlink" title="条形图（柱状图）"></a>条形图（柱状图）</h3><p>绘制柱状图的相关API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">mp.figure(<span class="string">'Bar'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.bar(</span><br><span class="line">	x,				<span class="comment"># 水平坐标数组</span></span><br><span class="line">    y,				<span class="comment"># 柱状图高度数组</span></span><br><span class="line">    width,			<span class="comment"># 柱子的宽度</span></span><br><span class="line">    color=<span class="string">''</span>, 		<span class="comment"># 填充颜色</span></span><br><span class="line">    label=<span class="string">''</span>,		<span class="comment">#</span></span><br><span class="line">    alpha=<span class="number">0.2</span>		<span class="comment">#</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>案例：先以柱状图绘制苹果12个月的销量，然后再绘制橘子的销量。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">apples = np.array([<span class="number">30</span>, <span class="number">25</span>, <span class="number">22</span>, <span class="number">36</span>, <span class="number">21</span>, <span class="number">29</span>, <span class="number">20</span>, <span class="number">24</span>, <span class="number">33</span>, <span class="number">19</span>, <span class="number">27</span>, <span class="number">15</span>])</span><br><span class="line">oranges = np.array([<span class="number">24</span>, <span class="number">33</span>, <span class="number">19</span>, <span class="number">27</span>, <span class="number">35</span>, <span class="number">20</span>, <span class="number">15</span>, <span class="number">27</span>, <span class="number">20</span>, <span class="number">32</span>, <span class="number">20</span>, <span class="number">22</span>])</span><br><span class="line">mp.figure(<span class="string">'Bar'</span>  , facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Bar'</span>, font size=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'Month'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'Price'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(axis=<span class="string">'y'</span>, linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.ylim((<span class="number">0</span>, <span class="number">40</span>))</span><br><span class="line">x = np.arange(len(apples))</span><br><span class="line">mp.bar(x<span class="number">-0.2</span>, apples, <span class="number">0.4</span>, color=<span class="string">'dodgerblue'</span>,label=<span class="string">'Apple'</span>)</span><br><span class="line">mp.bar(x + <span class="number">0.2</span>, oranges, <span class="number">0.4</span>, color=<span class="string">'orangered'</span>,label=<span class="string">'Orange'</span>, alpha=<span class="number">0.75</span>)</span><br><span class="line">mp.xticks(x, [</span><br><span class="line">    <span class="string">'Jan'</span>, <span class="string">'Feb'</span>, <span class="string">'Mar'</span>, <span class="string">'Apr'</span>, <span class="string">'May'</span>, <span class="string">'Jun'</span>,</span><br><span class="line">    <span class="string">'Jul'</span>, <span class="string">'Aug'</span>, <span class="string">'Sep'</span>, <span class="string">'Oct'</span>, <span class="string">'Nov'</span>, <span class="string">'Dec'</span>])</span><br><span class="line">mp.legend()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h3 id="饼图"><a href="#饼图" class="headerlink" title="饼图"></a>饼图</h3><p>绘制饼状图的基本API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">mp.pie(</span><br><span class="line">    values, 		<span class="comment"># 值列表		</span></span><br><span class="line">    spaces, 		<span class="comment"># 扇形之间的间距列表</span></span><br><span class="line">    labels, 		<span class="comment"># 标签列表</span></span><br><span class="line">    colors, 		<span class="comment"># 颜色列表</span></span><br><span class="line">    <span class="string">'%d%%'</span>,			<span class="comment"># 标签所占比例格式</span></span><br><span class="line">	shadow=<span class="literal">True</span>, 	<span class="comment"># 是否显示阴影</span></span><br><span class="line">    startangle=<span class="number">90</span>	<span class="comment"># 逆时针绘制饼状图时的起始角度</span></span><br><span class="line">    radius=<span class="number">1</span>		<span class="comment"># 半径</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>案例：绘制饼状图显示5门语言的流行程度：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">mp.figure(<span class="string">'pie'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line"><span class="comment">#整理数据</span></span><br><span class="line">values = [<span class="number">26</span>, <span class="number">17</span>, <span class="number">21</span>, <span class="number">29</span>, <span class="number">11</span>]</span><br><span class="line">spaces = [<span class="number">0.05</span>, <span class="number">0.01</span>, <span class="number">0.01</span>, <span class="number">0.01</span>, <span class="number">0.01</span>]</span><br><span class="line">labels = [<span class="string">'Python'</span>, <span class="string">'JavaScript'</span>,</span><br><span class="line">          <span class="string">'C++'</span>, <span class="string">'Java'</span>, <span class="string">'PHP'</span>]</span><br><span class="line">colors = [<span class="string">'dodgerblue'</span>, <span class="string">'orangered'</span>,</span><br><span class="line">          <span class="string">'limegreen'</span>, <span class="string">'violet'</span>, <span class="string">'gold'</span>]</span><br><span class="line">mp.figure(<span class="string">'Pie'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Pie'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line"><span class="comment"># 等轴比例</span></span><br><span class="line">mp.axis(<span class="string">'equal'</span>)</span><br><span class="line">mp.pie(</span><br><span class="line">    values, 		<span class="comment"># 值列表		</span></span><br><span class="line">    spaces, 		<span class="comment"># 扇形之间的间距列表</span></span><br><span class="line">    labels, 		<span class="comment"># 标签列表</span></span><br><span class="line">    colors, 		<span class="comment"># 颜色列表</span></span><br><span class="line">    <span class="string">'%d%%'</span>,			<span class="comment"># 标签所占比例格式</span></span><br><span class="line">	shadow=<span class="literal">True</span>, 	<span class="comment"># 是否显示阴影</span></span><br><span class="line">    startanle=<span class="number">90</span>	<span class="comment"># 逆时针绘制饼状图时的起始角度</span></span><br><span class="line">    radius=<span class="number">1</span>		<span class="comment"># 半径</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<h3 id="等高线图"><a href="#等高线图" class="headerlink" title="等高线图"></a>等高线图</h3><p>组成等高线需要网格点坐标矩阵，也需要每个点的高度。所以等高线属于3D数学模型范畴。</p>
<p>绘制等高线的相关API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">mp.contourf(x, y, z, <span class="number">8</span>, cmap=<span class="string">'jet'</span>)</span><br><span class="line">cntr = mp.contour(</span><br><span class="line">    x, 					<span class="comment"># 网格坐标矩阵的x坐标 （2维数组）</span></span><br><span class="line">    y, 					<span class="comment"># 网格坐标矩阵的y坐标 （2维数组）</span></span><br><span class="line">    z, 					<span class="comment"># 网格坐标矩阵的z坐标 （2维数组）</span></span><br><span class="line">    <span class="number">8</span>, 					<span class="comment"># 把等高线绘制成8部分</span></span><br><span class="line">    colors=<span class="string">'black'</span>,		<span class="comment"># 等高线的颜色</span></span><br><span class="line">	linewidths=<span class="number">0.5</span>		<span class="comment"># 线宽</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>案例：生成网格坐标矩阵，并且绘制等高线：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">n = <span class="number">1000</span></span><br><span class="line"><span class="comment"># 生成网格化坐标矩阵</span></span><br><span class="line">x, y = np.meshgrid(np.linspace(<span class="number">-3</span>, <span class="number">3</span>, n),</span><br><span class="line">                   np.linspace(<span class="number">-3</span>, <span class="number">3</span>, n))</span><br><span class="line"><span class="comment"># 根据每个网格点坐标，通过某个公式计算z高度坐标</span></span><br><span class="line">z = (<span class="number">1</span> - x/<span class="number">2</span> + x**<span class="number">5</span> + y**<span class="number">3</span>) * np.exp(-x**<span class="number">2</span> - y**<span class="number">2</span>)</span><br><span class="line">mp.figure(<span class="string">'Contour'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Contour'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line"><span class="comment"># 绘制等高线图</span></span><br><span class="line">mp.contourf(x, y, z, <span class="number">8</span>, cmap=<span class="string">'jet'</span>)</span><br><span class="line">cntr = mp.contour(x, y, z, <span class="number">8</span>, colors=<span class="string">'black'</span>,</span><br><span class="line">                  linewidths=<span class="number">0.5</span>)</span><br><span class="line"><span class="comment"># 为等高线图添加高度标签</span></span><br><span class="line">mp.clabel(cntr, inline_spacing=<span class="number">1</span>, fmt=<span class="string">'%.1f'</span>,</span><br><span class="line">          fontsize=<span class="number">10</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h3 id="热成像图"><a href="#热成像图" class="headerlink" title="热成像图"></a>热成像图</h3><p>用图形的方式显示矩阵及矩阵中值的大小<br>1 2 3<br>4 5 6<br>7 8 9</p>
<p>绘制热成像图的相关API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 把矩阵z图形化，使用cmap表示矩阵中每个元素值的大小</span></span><br><span class="line"><span class="comment"># origin: 坐标轴方向</span></span><br><span class="line"><span class="comment">#    upper: 缺省值，原点在左上角</span></span><br><span class="line"><span class="comment">#    lower: 原点在左下角</span></span><br><span class="line">mp.imshow(z, cmap=<span class="string">'jet'</span>, origin=<span class="string">'low'</span>)</span><br></pre></td></tr></table></figure>
<p>使用颜色条显示热度值：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mp.colorbar()</span><br></pre></td></tr></table></figure>
<h3 id="极坐标系"><a href="#极坐标系" class="headerlink" title="极坐标系"></a>极坐标系</h3><p>与笛卡尔坐标系不同，某些情况下极坐标系适合显示与角度有关的图像。例如雷达等。极坐标系可以描述极径&rho;与极角&theta;的线性关系。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mp.figure(<span class="string">"Polar"</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.gca(projection=<span class="string">'polar'</span>)</span><br><span class="line">mp.title(<span class="string">'Porlar'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">r'$\theta$'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">r'$\rho$'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<p>在极坐标系中绘制曲线：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#准备数据</span></span><br><span class="line">t = np.linspace(<span class="number">0</span>, <span class="number">4</span>*np.pi, <span class="number">1000</span>)</span><br><span class="line">r = <span class="number">0.8</span> * t</span><br><span class="line">mp.plot(t, r)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<p>案例，在极坐标系中绘制正弦函数。 y=3 sin(6x)</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">x = np.linspace(<span class="number">0</span>, <span class="number">6</span>*np.pi, <span class="number">1000</span>)</span><br><span class="line">y = <span class="number">3</span>*np.sin(<span class="number">6</span>*x)</span><br><span class="line">mp.plot(x, y)</span><br></pre></td></tr></table></figure>
<h3 id="3D图像绘制"><a href="#3D图像绘制" class="headerlink" title="3D图像绘制"></a>3D图像绘制</h3><p> matplotlib支持绘制三维曲面。若希望绘制三维曲面，需要使用axes3d提供的3d坐标系。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> mpl_toolkits.mplot3d <span class="keyword">import</span> axes3d</span><br><span class="line">ax3d = mp.gca(projection=<span class="string">'3d'</span>)   <span class="comment"># class axes3d</span></span><br></pre></td></tr></table></figure>
<p>matplotlib支持绘制三维点阵、三维曲面、三维线框图：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ax3d.scatter(..)		<span class="comment"># 绘制三维点阵</span></span><br><span class="line">ax3d.plot_surface(..)	<span class="comment"># 绘制三维曲面</span></span><br><span class="line">ax3d.plot_wireframe(..)	<span class="comment"># 绘制三维线框图</span></span><br></pre></td></tr></table></figure>
<p>3d散点图的绘制相关API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">ax3d.scatter(</span><br><span class="line">    x, 				<span class="comment"># x轴坐标数组</span></span><br><span class="line">    y,				<span class="comment"># y轴坐标数组</span></span><br><span class="line">    marker=<span class="string">''</span>, 		<span class="comment"># 点型</span></span><br><span class="line">    s=<span class="number">10</span>,			<span class="comment"># 大小</span></span><br><span class="line">    zorder=<span class="string">''</span>,		<span class="comment"># 图层序号</span></span><br><span class="line">    color=<span class="string">''</span>,		<span class="comment"># 颜色</span></span><br><span class="line">    edgecolor=<span class="string">''</span>, 	<span class="comment"># 边缘颜色</span></span><br><span class="line">    facecolor=<span class="string">''</span>,	<span class="comment"># 填充色</span></span><br><span class="line">    c=v,			<span class="comment"># 颜色值 根据cmap映射应用相应颜色</span></span><br><span class="line">    cmap=<span class="string">''</span>			<span class="comment"># </span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>案例：随机生成3组坐标，程标准正态分布规则，并且绘制它们。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">n = <span class="number">1000</span></span><br><span class="line">x = np.random.normal(<span class="number">0</span>, <span class="number">1</span>, n)</span><br><span class="line">y = np.random.normal(<span class="number">0</span>, <span class="number">1</span>, n)</span><br><span class="line">z = np.random.normal(<span class="number">0</span>, <span class="number">1</span>, n)</span><br><span class="line">d = np.sqrt(x ** <span class="number">2</span> + y ** <span class="number">2</span> + z ** <span class="number">2</span>)</span><br><span class="line">mp.figure(<span class="string">'3D Scatter'</span>)</span><br><span class="line">ax = mp.gca(projection=<span class="string">'3d'</span>)  <span class="comment"># 创建三维坐标系</span></span><br><span class="line">mp.title(<span class="string">'3D Scatter'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">ax.set_xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">ax.set_ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">ax.set_zlabel(<span class="string">'z'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">ax.scatter(x, y, z, s=<span class="number">60</span>, c=d, cmap=<span class="string">'jet_r'</span>, alpha=<span class="number">0.5</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<p>3d平面图的绘制相关API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">ax3d.plot_surface(</span><br><span class="line">    x, 					<span class="comment"># 网格坐标矩阵的x坐标 （2维数组）</span></span><br><span class="line">    y, 					<span class="comment"># 网格坐标矩阵的y坐标 （2维数组）</span></span><br><span class="line">    z, 					<span class="comment"># 网格坐标矩阵的z坐标 （2维数组）</span></span><br><span class="line">    rstride=<span class="number">30</span>,			<span class="comment"># 行跨距</span></span><br><span class="line">    cstride=<span class="number">30</span>, 		<span class="comment"># 列跨距</span></span><br><span class="line">    cmap=<span class="string">'jet'</span>			<span class="comment"># 颜色映射</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>案例：绘制3d平面图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">n = <span class="number">1000</span></span><br><span class="line"><span class="comment"># 生成网格化坐标矩阵</span></span><br><span class="line">x, y = np.meshgrid(np.linspace(<span class="number">-3</span>, <span class="number">3</span>, n),</span><br><span class="line">                   np.linspace(<span class="number">-3</span>, <span class="number">3</span>, n))</span><br><span class="line"><span class="comment"># 根据每个网格点坐标，通过某个公式计算z高度坐标</span></span><br><span class="line">z = (<span class="number">1</span> - x/<span class="number">2</span> + x**<span class="number">5</span> + y**<span class="number">3</span>) * np.exp(-x**<span class="number">2</span> - y**<span class="number">2</span>)</span><br><span class="line">mp.figure(<span class="string">'3D'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line"></span><br><span class="line">ax3d = mp.gca(projection=<span class="string">'3d'</span>)</span><br><span class="line">mp.title(<span class="string">'3D'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">ax3d.set_xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">ax3d.set_ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">ax3d.set_zlabel(<span class="string">'z'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line"><span class="comment"># 绘制3D平面图</span></span><br><span class="line"><span class="comment"># rstride: 行跨距</span></span><br><span class="line"><span class="comment"># cstride: 列跨距 </span></span><br><span class="line">ax3d.plot_surface(x,y,z,rstride=<span class="number">30</span>,cstride=<span class="number">30</span>, cmap=<span class="string">'jet'</span>)</span><br></pre></td></tr></table></figure>
<p>案例：3d线框图的绘制</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 绘制3D平面图 </span></span><br><span class="line"><span class="comment"># rstride: 行跨距</span></span><br><span class="line"><span class="comment"># cstride: 列跨距 </span></span><br><span class="line">ax3d.plot_wireframe(x,y,z,rstride=<span class="number">30</span>,cstride=<span class="number">30</span>, </span><br><span class="line">	linewidth=<span class="number">1</span>, color=<span class="string">'dodgerblue'</span>)</span><br></pre></td></tr></table></figure>
<h3 id="简单动画"><a href="#简单动画" class="headerlink" title="简单动画"></a>简单动画</h3><p>动画即是在一段时间内快速连续的重新绘制图像的过程。</p>
<p>matplotlib提供了方法用于处理简单动画的绘制。定义update函数用于即时更新图像。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> matplotlib.animation <span class="keyword">as</span> ma</span><br><span class="line"><span class="comment">#定义更新函数行为</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">update</span><span class="params">(number)</span>:</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="comment"># 每隔10毫秒执行一次update更新函数，作用于mp.gcf()当前窗口对象</span></span><br><span class="line"><span class="comment"># mp.gcf()：	获取当前窗口</span></span><br><span class="line"><span class="comment"># update：	更新函数</span></span><br><span class="line"><span class="comment"># interval：	间隔时间（单位：毫秒）</span></span><br><span class="line">anim = ma.FuncAnimation(mp.gcf(), update, interval=<span class="number">10</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<p>案例：随机生成各种颜色的100个气泡。让他们不断的增大。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#自定义一种可以存放在ndarray里的类型，用于保存一个球</span></span><br><span class="line">ball_type = np.dtype([</span><br><span class="line">	(<span class="string">'position'</span>, float, <span class="number">2</span>),  <span class="comment"># 位置(水平和垂直坐标)</span></span><br><span class="line">    (<span class="string">'size'</span>, float, <span class="number">1</span>),      <span class="comment"># 大小</span></span><br><span class="line">    (<span class="string">'growth'</span>, float, <span class="number">1</span>),    <span class="comment"># 生长速度</span></span><br><span class="line">    (<span class="string">'color'</span>, float, <span class="number">4</span>)])    <span class="comment"># 颜色(红、绿、蓝和透明度)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#随机生成100个点对象</span></span><br><span class="line">n = <span class="number">100</span></span><br><span class="line">balls = np.zeros(<span class="number">100</span>, dtype=ball_type)</span><br><span class="line">balls[<span class="string">'position'</span>]=np.random.uniform(<span class="number">0</span>, <span class="number">1</span>, (n, <span class="number">2</span>))</span><br><span class="line">balls[<span class="string">'size'</span>]=np.random.uniform(<span class="number">40</span>, <span class="number">70</span>, n)</span><br><span class="line">balls[<span class="string">'growth'</span>]=np.random.uniform(<span class="number">10</span>, <span class="number">20</span>, n)</span><br><span class="line">balls[<span class="string">'color'</span>]=np.random.uniform(<span class="number">0</span>, <span class="number">1</span>, (n, <span class="number">4</span>))</span><br><span class="line"></span><br><span class="line">mp.figure(<span class="string">"Animation"</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">"Animation"</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.xticks </span><br><span class="line">mp.yticks(())</span><br><span class="line"></span><br><span class="line">sc = mp.scatter(</span><br><span class="line">	balls[<span class="string">'position'</span>][:, <span class="number">0</span>], </span><br><span class="line">	balls[<span class="string">'position'</span>][:, <span class="number">1</span>], </span><br><span class="line">	balls[<span class="string">'size'</span>], </span><br><span class="line">	color=balls[<span class="string">'color'</span>], alpha=<span class="number">0.5</span>)</span><br><span class="line">	</span><br><span class="line"><span class="comment">#定义更新函数行为</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">update</span><span class="params">(number)</span>:</span></span><br><span class="line">	balls[<span class="string">'size'</span>] += balls[<span class="string">'growth'</span>]</span><br><span class="line">	<span class="comment">#每次让一个气泡破裂，随机生成一个新的</span></span><br><span class="line">	boom_ind = number % n</span><br><span class="line">	balls[boom_ind][<span class="string">'size'</span>]=np.random.uniform(<span class="number">40</span>, <span class="number">70</span>, <span class="number">1</span>)</span><br><span class="line">	balls[boom_ind][<span class="string">'position'</span>]=np.random.uniform(<span class="number">0</span>, <span class="number">1</span>, (<span class="number">1</span>, <span class="number">2</span>))</span><br><span class="line">	<span class="comment"># 重新设置属性</span></span><br><span class="line">	sc.set_sizes(balls[<span class="string">'size'</span>])</span><br><span class="line">	sc.set_offsets(balls[<span class="string">'position'</span>])</span><br><span class="line">	</span><br><span class="line"><span class="comment"># 每隔30毫秒执行一次update更新函数，作用于mp.gcf()当前窗口对象</span></span><br><span class="line"><span class="comment"># mp.gcf()：	获取当前窗口</span></span><br><span class="line"><span class="comment"># update：		更新函数</span></span><br><span class="line"><span class="comment"># interval：	间隔时间（单位：毫秒）</span></span><br><span class="line">anim = ma.FuncAnimation(mp.gcf(), update, interval=<span class="number">30</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<p>使用生成器函数提供数据，实现动画绘制</p>
<p>在很多情况下，绘制动画的参数是动态获取的，matplotlib支持定义generator生成器函数，用于生成数据，把生成的数据交给update函数更新图像：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> matplotlib.animation <span class="keyword">as</span> ma</span><br><span class="line"><span class="comment">#定义更新函数行为</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">update</span><span class="params">(data)</span>:</span></span><br><span class="line">    t, v = data</span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">generator</span><span class="params">()</span>:</span></span><br><span class="line">	<span class="keyword">yield</span> t, v</span><br><span class="line">        </span><br><span class="line"><span class="comment"># 每隔10毫秒将会先调用生成器，获取生成器返回的数据，</span></span><br><span class="line"><span class="comment"># 把生成器返回的数据交给并且调用update函数，执行更新图像函数</span></span><br><span class="line">anim = ma.FuncAnimation(mp.gcf(), update, generator,interval=<span class="number">10</span>)</span><br></pre></td></tr></table></figure>
<p>案例：绘制信号曲线：y=sin(2 <em> π </em> t) <em> exp(sin(0.2 </em> π * t))，数据通过生成器函数生成，在update函数中绘制曲线。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">mp.figure(<span class="string">"Signal"</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">"Signal"</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.xlim(<span class="number">0</span>, <span class="number">10</span>)</span><br><span class="line">mp.ylim(<span class="number">-3</span>, <span class="number">3</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">'--'</span>, color=<span class="string">'lightgray'</span>, alpha=<span class="number">0.5</span>)</span><br><span class="line">pl = mp.plot([], [], color=<span class="string">'dodgerblue'</span>, label=<span class="string">'Signal'</span>)[<span class="number">0</span>]</span><br><span class="line">pl.set_data([],[])</span><br><span class="line"></span><br><span class="line">x = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">update</span><span class="params">(data)</span>:</span></span><br><span class="line">	t, v = data</span><br><span class="line">	x, y = pl.get_data()</span><br><span class="line">	x.append(t)</span><br><span class="line">	y.append(v)</span><br><span class="line">	<span class="comment">#重新设置数据源</span></span><br><span class="line">	pl.set_data(x, y)</span><br><span class="line">	<span class="comment">#移动坐标轴</span></span><br><span class="line">	<span class="keyword">if</span>(x[<span class="number">-1</span>]&gt;<span class="number">10</span>):</span><br><span class="line">		mp.xlim(x[<span class="number">-1</span>]<span class="number">-10</span>, x[<span class="number">-1</span>])</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">y_generator</span><span class="params">()</span>:</span></span><br><span class="line">	<span class="keyword">global</span> x</span><br><span class="line">	y = np.sin(<span class="number">2</span> * np.pi * x) * np.exp(np.sin(<span class="number">0.2</span> * np.pi * x))</span><br><span class="line">	<span class="keyword">yield</span> (x, y)</span><br><span class="line">	x += <span class="number">0.05</span></span><br><span class="line"></span><br><span class="line">anim = ma.FuncAnimation(mp.gcf(), update, y_generator, interval=<span class="number">20</span>)</span><br><span class="line">mp.tight_layout()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h2 id="其他Python的绘图库"><a href="#其他Python的绘图库" class="headerlink" title="其他Python的绘图库"></a>其他Python的绘图库</h2><p><span class="exturl" data-url="aHR0cDovL3B5ZWNoYXJ0cy5oZXJva3VhcHAuY29tLw==" title="http://pyecharts.herokuapp.com/">pyecharts<i class="fa fa-external-link"></i></span></p>
<h2 id="附录"><a href="#附录" class="headerlink" title="附录"></a>附录</h2><h3 id="linestyle"><a href="#linestyle" class="headerlink" title="linestyle"></a>linestyle</h3><div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:left">字符</th>
<th style="text-align:left">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">‘-‘</td>
<td style="text-align:left">实线样式</td>
</tr>
<tr>
<td style="text-align:left">‘—‘</td>
<td style="text-align:left">短横线样式</td>
</tr>
<tr>
<td style="text-align:left">‘-.’</td>
<td style="text-align:left">点划线样式</td>
</tr>
<tr>
<td style="text-align:left">‘:’</td>
<td style="text-align:left">虚线样式</td>
</tr>
<tr>
<td style="text-align:left">‘.’</td>
<td style="text-align:left">点标记</td>
</tr>
<tr>
<td style="text-align:left">‘,’</td>
<td style="text-align:left">像素标记</td>
</tr>
<tr>
<td style="text-align:left">‘o’</td>
<td style="text-align:left">圆标记</td>
</tr>
<tr>
<td style="text-align:left">‘v’</td>
<td style="text-align:left">倒三角标记</td>
</tr>
<tr>
<td style="text-align:left">‘^’</td>
<td style="text-align:left">正三角标记</td>
</tr>
<tr>
<td style="text-align:left">‘&lt;’</td>
<td style="text-align:left">左三角标记</td>
</tr>
<tr>
<td style="text-align:left">‘&gt;’</td>
<td style="text-align:left">右三角标记</td>
</tr>
<tr>
<td style="text-align:left">‘1’</td>
<td style="text-align:left">下箭头标记</td>
</tr>
<tr>
<td style="text-align:left">‘2’</td>
<td style="text-align:left">上箭头标记</td>
</tr>
<tr>
<td style="text-align:left">‘3’</td>
<td style="text-align:left">左箭头标记</td>
</tr>
<tr>
<td style="text-align:left">‘4’</td>
<td style="text-align:left">右箭头标记</td>
</tr>
<tr>
<td style="text-align:left">‘s’</td>
<td style="text-align:left">正方形标记</td>
</tr>
<tr>
<td style="text-align:left">‘p’</td>
<td style="text-align:left">五边形标记</td>
</tr>
<tr>
<td style="text-align:left">‘*’</td>
<td style="text-align:left">星形标记</td>
</tr>
<tr>
<td style="text-align:left">‘h’</td>
<td style="text-align:left">六边形标记 1</td>
</tr>
<tr>
<td style="text-align:left">‘H’</td>
<td style="text-align:left">六边形标记 2</td>
</tr>
<tr>
<td style="text-align:left">‘+’</td>
<td style="text-align:left">加号标记</td>
</tr>
<tr>
<td style="text-align:left">‘x’</td>
<td style="text-align:left">X 标记</td>
</tr>
<tr>
<td style="text-align:left">‘D’</td>
<td style="text-align:left">菱形标记</td>
</tr>
<tr>
<td style="text-align:left">‘d’</td>
<td style="text-align:left">窄菱形标记</td>
</tr>
<tr>
<td style="text-align:left">‘&#124;’</td>
<td style="text-align:left">竖直线标记</td>
</tr>
<tr>
<td style="text-align:left">‘_’</td>
<td style="text-align:left">水平线标记</td>
</tr>
</tbody>
</table>
</div>
<blockquote>
<p>上面是网上找的，但是实际测试中只有’-‘, ‘—‘, ‘-.’, ‘:’, ‘None’, ‘ ‘, ‘’, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’可以用</p>
</blockquote>
<h3 id="linecolor"><a href="#linecolor" class="headerlink" title="linecolor"></a>linecolor</h3><p><img src="https://object.renchengqi.com/blog/h0wl9.png" alt></p>
<h3 id="laTex排版语法"><a href="#laTex排版语法" class="headerlink" title="laTex排版语法"></a>laTex排版语法</h3><p>laTeX语法表示数学符号示例<br><img src="https://object.renchengqi.com/blog/ku31o.png" alt><br>LaTeX语法集合<br><img src="https://object.renchengqi.com/blog/x8an5.gif" alt></p>
<h3 id="cmap颜色映射表"><a href="#cmap颜色映射表" class="headerlink" title="cmap颜色映射表"></a>cmap颜色映射表</h3><p><img src="https://object.renchengqi.com/blog/whkot.png" alt></p>
<h3 id="point样式"><a href="#point样式" class="headerlink" title="point样式"></a>point样式</h3><p><img src="https://object.renchengqi.com/blog/omq6w.png" alt></p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/数据分析/" rel="tag"># 数据分析</a>
          
            <a href="/tags/AI进阶/" rel="tag"># AI进阶</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/30/datascience/Numpy/" rel="next" title="Numpy">
                <i class="fa fa-chevron-left"></i> Numpy
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/02/09/ml/概述/" rel="prev" title="机器学习-概述">
                机器学习-概述 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.JPG" alt="任成">
            
              <p class="site-author-name" itemprop="name">任成</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0NvZGVyQ3VydmU=" title="GitHub &rarr; https://github.com/CoderCurve"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOnJlbmNoZW5nMTFAaWNsb3VkLmNvbQ==" title="E-Mail &rarr; mailto:rencheng11@icloud.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#概述"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#matplotlib基本功能"><span class="nav-number">1.1.</span> <span class="nav-text">matplotlib基本功能</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基本绘图"><span class="nav-number">2.</span> <span class="nav-text">基本绘图</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#绘制水平线与垂直线："><span class="nav-number">2.1.</span> <span class="nav-text">绘制水平线与垂直线：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线型、线宽和颜色"><span class="nav-number">2.2.</span> <span class="nav-text">线型、线宽和颜色</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置坐标轴范围"><span class="nav-number">2.3.</span> <span class="nav-text">设置坐标轴范围</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置坐标刻度"><span class="nav-number">2.4.</span> <span class="nav-text">设置坐标刻度</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置坐标轴"><span class="nav-number">2.5.</span> <span class="nav-text">设置坐标轴</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#图例"><span class="nav-number">2.6.</span> <span class="nav-text">图例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#特殊点"><span class="nav-number">2.7.</span> <span class="nav-text">特殊点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#备注"><span class="nav-number">2.8.</span> <span class="nav-text">备注</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#图形对象（图形窗口）"><span class="nav-number">3.</span> <span class="nav-text">图形对象（图形窗口）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#子图"><span class="nav-number">3.1.</span> <span class="nav-text">子图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#刻度定位器"><span class="nav-number">3.2.</span> <span class="nav-text">刻度定位器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#刻度网格线"><span class="nav-number">3.3.</span> <span class="nav-text">刻度网格线</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#半对数坐标"><span class="nav-number">3.4.</span> <span class="nav-text">半对数坐标</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#散点图"><span class="nav-number">3.5.</span> <span class="nav-text">散点图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#填充"><span class="nav-number">3.6.</span> <span class="nav-text">填充</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#条形图（柱状图）"><span class="nav-number">3.7.</span> <span class="nav-text">条形图（柱状图）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#饼图"><span class="nav-number">3.8.</span> <span class="nav-text">饼图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#等高线图"><span class="nav-number">3.9.</span> <span class="nav-text">等高线图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#热成像图"><span class="nav-number">3.10.</span> <span class="nav-text">热成像图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#极坐标系"><span class="nav-number">3.11.</span> <span class="nav-text">极坐标系</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3D图像绘制"><span class="nav-number">3.12.</span> <span class="nav-text">3D图像绘制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#简单动画"><span class="nav-number">3.13.</span> <span class="nav-text">简单动画</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他Python的绘图库"><span class="nav-number">4.</span> <span class="nav-text">其他Python的绘图库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#附录"><span class="nav-number">5.</span> <span class="nav-text">附录</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#linestyle"><span class="nav-number">5.1.</span> <span class="nav-text">linestyle</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#linecolor"><span class="nav-number">5.2.</span> <span class="nav-text">linecolor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#laTex排版语法"><span class="nav-number">5.3.</span> <span class="nav-text">laTex排版语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cmap颜色映射表"><span class="nav-number">5.4.</span> <span class="nav-text">cmap颜色映射表</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#point样式"><span class="nav-number">5.5.</span> <span class="nav-text">point样式</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备18001214号 </span>&copy; 2014 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">任成</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
    <span title="站点总字数">277k</span>
  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'forest',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  

  

  

  

  

  

  

  

  

</body>
</html>
